import styles from "./style.module.less";
import { getFileLocalUrl, getFileName } from "@/utils/tools";
export default defineComponent({
  name: "UploadAvatar",
  props: {
    modelValue: {
      type: String,
      default: "",
    },
    accept: {
      // 接受的文件类型
      type: String,
      default: "image/*",
    },
    showUploadList: {
      type: [Object, Boolean],
      default: false,
    },
    isShowDelete: {
      type: [Object, Boolean],
      default: true,
    },
  },
  emits: ["update:modelValue"],
  setup(props, { attrs, emit, expose, slots }) {
    const fileSrc = ref<string>(props.modelValue);
    const loading = ref<boolean>(false);
    const tipText = ref<string>("上传中...");
    const setFileSrc = (file: File) => {
      getFileLocalUrl(file)
        .then((url) => (fileSrc.value = url))
        .catch((err) => {
          console.log(err);
        });
    };
    const removeFile = () => {
      fileSrc.value = "";
      emit("update:modelValue", fileSrc.value);
    };
    const beforeUpload = (file: any) => true;
    const selfUpload = async (target: any) => {
      try {
        loading.value = true;
        // setFileSrc(target.file);
        removeFile();
        const formData = new FormData();
        formData.append("avatar", target.file);
        const res: any = await userApi.uploadAvatar(formData, {
          onUploadProgress: function (progressEvent) {
            const progress = Math.round(
              (progressEvent.loaded * 100) / progressEvent.total
            );
            tipText.value = `${progress}%`;
          },
        });
        if (res.code === 200) {
          message.success($t("base.uploadSuccess"));
          fileSrc.value = res?.data?.img_url;
          emit("update:modelValue", fileSrc.value);
        } else {
          message.error(`${$t("base.uploadFailed")}: ${res.message}`);
        }
      } catch (error: any) {
        message.error(`${$t("base.uploadFailed")}: ${error.message}`);
      } finally {
        loading.value = false;
      }
    };
    const isPreview = ref<boolean>(false);
    const setIsPreview = (visible: boolean) => (isPreview.value = visible);
    return () => (
      <>
        <div class={styles.container}>
          {fileSrc.value ? (
            <a-image
              class={styles.img}
              width={102}
              height={102}
              src={fileSrc.value}
              preview={{
                visible: isPreview.value,
                onVisibleChange: setIsPreview,
              }}
              placeholder
            />
          ) : null}

          {loading.value ? (
            <div class={styles.layout}>
              <a-spin tip={tipText.value} />
            </div>
          ) : fileSrc.value ? (
            <div class={[styles.layout, styles.edit]}>
              <eye-outlined
                style="cursor: pointer;"
                onClick={() => setIsPreview(true)}
              />
              {props.isShowDelete ? (
                <delete-outlined
                  style="cursor: pointer;"
                  onClick={removeFile}
                />
              ) : null}
            </div>
          ) : (
            <a-upload
              accept={props.accept}
              openFileDialogOnClick={true}
              disabled={loading.value}
              beforeUpload={beforeUpload}
              customRequest={selfUpload}
              list-type="picture-card"
            >
              <div>
                <plus-outlined />
                <div class="ant-upload-text">{$t("base.uploadImg")}</div>
              </div>
            </a-upload>
          )}
        </div>
      </>
    );
  },
});
